import React, { Component } from 'react'
import './index.css'
import {Flipper,formatDate} from './common'

// 翻牌时钟的实现
export default class AnimateNum2 extends Component {

  componentDidMount(){
    // 定位时钟模块
      let clock = document.getElementById('clock')
      // 定位6个翻板
      let flips = clock.querySelectorAll('.flip')
      // 获取当前时间
      let now = new Date()
      // 格式化当前时间，例如现在是20:30:10，则输出"203010"字符串
      let nowTimeStr = formatDate(now, 'hhiiss')
      // 格式化下一秒的时间
      let nextTimeStr = formatDate(new Date(now.getTime() + 1000), 'hhiiss')
      // 定义牌板数组，用来存储6个Flipper翻板对象
      let flipObjs = []
      for (let i = 0; i < flips.length; i++) {
          // 创建6个Flipper实例，初始化并存入flipObjs
          flipObjs.push(new Flipper({
              // 每个Flipper实例按数组顺序与翻板DOM的顺序一一对应
              node: flips[i],
              // 按数组顺序取时间字符串对应位置的数字
              frontText: 'number' + nowTimeStr[i],
              backText: 'number' + nextTimeStr[i]
          }))
      }

      setInterval(function() {
        // 获取当前时间
        let now = new Date()
        // 格式化当前时间
        let nowTimeStr = formatDate(new Date(now.getTime() - 1000), 'hhiiss')
        // 格式化下一秒时间
        let nextTimeStr = formatDate(now, 'hhiiss')
        // 将当前时间和下一秒时间逐位对比
        for (let i = 0; i < flipObjs.length; i++) {
            // 如果前后数字没有变化，则直接跳过，不翻牌
            if (nowTimeStr[i] === nextTimeStr[i]) {
                continue
            }
            // 传递前后牌的数字，进行向下翻牌动画
            flipObjs[i].flipDown('number' + nowTimeStr[i], 'number' + nextTimeStr[i])
        }
    }, 1000)
  }

  render() {
    return (
      <div class="clock" id="clock">
        <div class="flip down">
            <div class="digital front number0"></div>
            <div class="digital back number1"></div>
        </div>
        <div class="flip down">
            <div class="digital front number0"></div>
            <div class="digital back number1"></div>
        </div>
        <em>:</em>
        <div class="flip down">
            <div class="digital front number0"></div>
            <div class="digital back number1"></div>
        </div>
        <div class="flip down">
            <div class="digital front number0"></div>
            <div class="digital back number1"></div>
        </div>
        <em>:</em>
        <div class="flip down">
            <div class="digital front number0"></div>
            <div class="digital back number1"></div>
        </div>
        <div class="flip down">
            <div class="digital front number0"></div>
            <div class="digital back number1"></div>
        </div>
    </div>
    )
  }
}